package nl.hu.verbrandendephoenix.controller;

import java.util.ArrayList;

import nl.hu.verbrandendephoenix.client.AppManager;
import nl.hu.verbrandendephoenix.client.NotificationManager;
import nl.hu.verbrandendephoenix.shared.Auction;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Panel;

public class MyAuctions {

	private nl.hu.verbrandendephoenix.view.MyAuctions myAuctionsForm;
	private ArrayList<Auction> auctionarr;

	public MyAuctions(){

	}

	public Panel getPanel(){
		myAuctionsForm = new nl.hu.verbrandendephoenix.view.MyAuctions();
		Panel p = myAuctionsForm.constructForm();
		getData();
		addHandlers();


		return p;

	}

	public void getData() {
		final NotificationManager nM = NotificationManager.get();

		AppManager.get().getRpcService().getMyAuctions(Cookies.getCookie("loginString"), new AsyncCallback<ArrayList<Auction>>() {
			public void onFailure(Throwable caught) {
				nM.commError();
			}
			public void onSuccess(ArrayList<Auction> auctions) {
				auctionarr = auctions;
				setData(auctions);
			}

		});
	}

	public void setData(ArrayList<Auction> myAuctions){

		GWT.log(myAuctions.toString());
		for(Auction auction : myAuctions){
			myAuctionsForm.boxAuctions.addItem(auction.getAuctionName());
		}
	}
	
	public void addHandlers() {
		Button btnConfirm = myAuctionsForm.getBtnSubmit();
		btnConfirm.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				int keuze = myAuctionsForm.boxAuctions.getSelectedIndex();
				String auction = myAuctionsForm.boxAuctions.getValue(keuze);
				final NotificationManager nM =  NotificationManager.get();
				if(auction == "Selecteer een veiling"){
					nM.createNotification("U heeft geen veiling geselecteerd");
				}else{
					int arrIndex = keuze - 1;
					processSubmit(arrIndex);
				} 
			}
		});
	}
	
	public void processSubmit(int keuze) {
		auctionarr.get(keuze).toString();
		Auction a = auctionarr.get(keuze);
		String tag = Integer.toString(a.getAuctionID());
		History.newItem("viewauction-"+tag);
	}
}
